import store from '@/store'
import router from '@/router/index'
import {getToken} from '../utils/auth';
import axios from 'axios'
import { Message, Loading } from 'element-ui'
import lodash from 'lodash';//npm i lodash
const service = axios.create({
  baseURL: '',
  timeout: 30000
})

let loading;
let needLoadingRequestCount = 0;//当前正在请求的数量
let downloadLoadingInstance;
//显示loading
function showLoading(target) {
  // 关闭时加了抖动，此时loading对象可能还存在，但needLoadingRequestCount已经变成0.避免这种情况下会重新创建个loading
  if (needLoadingRequestCount === 0 && !loading) {
    loading = Loading.service({
      lock: true,
      text: "Loading...",
      background: 'rgba(255, 255, 255, 0.5)',
      target: target
    });
  }
  needLoadingRequestCount++;
}
//隐藏loading
function hideLoading() {
  needLoadingRequestCount--;
  needLoadingRequestCount = Math.max(needLoadingRequestCount, 0); //做个保护
  if (needLoadingRequestCount === 0) {
    toHideLoading();
  }
}
//防抖：将 300ms 间隔内的关闭 loading 便合并为一次。防止连续请求时， loading闪烁的问题。
var toHideLoading = lodash.debounce(() => {
  loading.close();
  loading = null;
}, 300);
//添加请求拦截器
service.interceptors.request.use(config => {
    config.headers['token'] =getToken()
  if (config.headers.showLoading !== false) {  //判断当前请求是否设置了不显示Loading
    showLoading(config.headers.loadingTarget);
  }
  return config;
}, err => {
  if (config.headers.showLoading !== false) {  //判断当前请求是否设置了不显示Loading
    hideLoading();
  }
  Message.error('请求超时!');
  return Promise.resolve(err);
});
//响应拦截器
service.interceptors.response.use(

  res => {
    //   if (res.data.code == 2000) {
    //     res.data.code=200
    //  }
    //判断当前请求是否设置了不显示Loading（不显示自然无需隐藏） headers 无 showLoading  末日就有loading
    if (res.config.headers.showLoading !== false) {
      hideLoading();
    }
    if (res.data.code == 401) {
      // Message({ type: 'warning', message: res.data.msg });
      // location.href = '/Setting';
      // router.push('/Setting')
      // localStorage.removeItem('accessToken')
    }
    return res.data;
  },
  err => {
    //判断当前请求是否设置了不显示Loading（不显示自然无需隐藏）
    if (err.config.headers.showLoading !== false) {
      hideLoading();
    }
    if (err.response && err.response.data && err.response.data.message) {
      var jsonObj = JSON.parse(err.response.data.message);
      Message.error(jsonObj.message);
    } else {
      Message.error('错误');
    }
    return Promise.reject(err);
  }
);
// 通用下载方法
export function download(url, params, filename, config) {
  downloadLoadingInstance = Loading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
  return service.post(url, params, {
    transformRequest: [(params) => { return tansParams(params) }],
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    responseType: 'blob',
    ...config
  }).then(async (data) => {
    const isBlob = blobValidate(data);
    if (isBlob) {
      const blob = new Blob([data])
      saveAs(blob, filename)
    } else {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
      Message.error(errMsg);
    }
    downloadLoadingInstance.close();
  }).catch((r) => {
    console.error(r)
    Message.error('下载文件出现错误，请联系管理员！')
    downloadLoadingInstance.close();
  })
}
export default service
